package com.example.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.retry.annotation.Backoff;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@Component
public class LlmClientUtil {
    private static final Logger log = LoggerFactory.getLogger(LlmClientUtil.class);
    private final String apiKey;
    private final String baseUrl;
    private final RestTemplate restTemplate;

    public LlmClientUtil(
            @Value("${spring.ai.deepseek.api-key}") String apiKey,
            @Value("${spring.ai.deepseek.base-url:https://api.deepseek.com}") String baseUrl) {

        this.apiKey = apiKey;
        // 确保 baseUrl 包含 /v1
        this.baseUrl = baseUrl.endsWith("/v1") ? baseUrl : baseUrl + "/v1";
        this.restTemplate = new RestTemplate();

        log.info("DeepSeek API 配置：BaseUrl={}", this.baseUrl);
    }

    @Retryable(value = Exception.class, maxAttempts = 3, backoff = @Backoff(delay = 1000))
    public String callLlm(String prompt) {
        try {
            log.debug("调用DeepSeek，提示词长度：{}", prompt.length());

            String url = baseUrl + "/chat/completions";

            // 构建请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));

            // 构建请求体 - 使用 DeepSeek 要求的格式
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("model", "deepseek-chat");
            requestBody.put("temperature", 0.3);
            requestBody.put("max_tokens", 2048);
            requestBody.put("stream", false);

            // 构建 messages 数组
            List<Map<String, String>> messages = new ArrayList<>();
            Map<String, String> message = new HashMap<>();
            message.put("role", "user");
            message.put("content", prompt);
            messages.add(message);

            requestBody.put("messages", messages);

            HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

            log.debug("发送请求到: {}", url);

            // 发送请求
            ResponseEntity<Map> response = restTemplate.exchange(
                    url, HttpMethod.POST, entity, Map.class);

            // 解析响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                Map<String, Object> responseBody = response.getBody();

                if (responseBody.containsKey("choices")) {
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) responseBody.get("choices");
                    if (!choices.isEmpty()) {
                        Map<String, Object> choice = choices.get(0);
                        Map<String, Object> messageResponse = (Map<String, Object>) choice.get("message");
                        String content = (String) messageResponse.get("content");

                        log.debug("DeepSeek返回结果长度：{}", content.length());
                        return content;
                    }
                }
                throw new RuntimeException("Invalid response format from DeepSeek API: " + responseBody);
            } else {
                throw new RuntimeException("HTTP error: " + response.getStatusCode());
            }
        } catch (Exception e) {
            log.error("DeepSeek调用失败（重试中）- 错误信息: {}", e.getMessage(), e);
            throw new RuntimeException("DeepSeek API调用失败: " + e.getMessage(), e);
        }
    }
}